/**将原始路由URL参数中加入路由标记 */
export function changeRouterUrl(url, key) {
  const routerParams = getUrlParam(url) || {}
  routerParams[key] = getPageInfo().routeID + ""
  let _url = urlEncode(routerParams)
  if (_url[0] === "&") {
    _url = _url.replace("&", "?")
  }
  return {
    url: url.split("?")[0] + (_url || ""),
    key: routerParams[key]
  }
}


// export interface TypeUseFunceion { (res: { router: string; data: object }, next: (res?) => void, error: (msg?: string) => void): void }
export class MyCompose {
   useFunctions = []

  /**
   * 初始化函数执行前需要执行的函数
  */
   use(fn) {
    if (typeof fn === 'function' && Array.isArray(this.useFunctions)) {
      this.useFunctions.push(fn)
    }
  }
  /**
   * 依次使用use函数传入的函数
  */
   runUse(cxt) {
    let i = 0
    let useFns = [...this.useFunctions]
    return new Promise((resolve, reject) => {
      function next() {
        const nextFn = useFns[i];
        i++
        if (!nextFn || typeof nextFn !== 'function') {
          resolve(true)
          return
        }
        nextFn(cxt, next.bind(this), reject);
      }
      next.call(this);
    })
  }
}


/**
 * 转换url参数
 * @param url
 * @returns
 */
 export function getUrlParam(url) {
  let query = null;
  function run(_str) {
    const pairs = _str.split("&");
    for (let i = 0; i < pairs.length; i++) {
      if (query == null) query = {}
      const pair = pairs[i].split("=");
      let _data = null
      if (pair[1] === "null") {
        _data = null
      } else if (pair[1] === "false") {
        _data = false
      } else if (pair[1] === "true") {
        _data = true
      } else if (pair[1] === "undefined") {
        _data = undefined
      } else {
        _data = pair[1];
      }
      query[pair[0]] = _data
    }
  }
  if (url.indexOf("?") != -1) {
    url = "?" + url.split("?")[1]
    const str = url.substr(1);
    run(str)
  } else {
    run(url)
  }
  return query;  // 返回对象
}
export function urlEncode(param, key, encode) {
  if (param == null) return '';
  var paramStr = '';
  var t = typeof (param);
  if (t == 'string' || t == 'number' || t == 'boolean') {
    paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param);
  } else {
    for (var i in param) {
      var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
      paramStr += urlEncode(param[i], k, encode);
    }
  }
  return paramStr;
};
/**
 * 获取页面数据
 */
export function getPageInfo() {
  const _pages = getCurrentPages()
  const _now = _pages[_pages.length - 1]
  const list = _pages.map(val => {
    return {
      url: "/" + val?.route,
      routeID: val.__wxWebviewId__
    }
  })
  return {
    route: "/" + _now?.route,
    routeID: _now?.__wxWebviewId__,
    list
  }
}
export function getUUid() {
  //生成一个UUID
  var s = [];
  var hexDigits = "0123456789abcdef";
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr(((s['19']) & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = "";

  var uuid = s.join("");
  return uuid;
}
/**
 * 深拷贝
*/
export function deepClone(obj) {
  if (typeof obj !== 'object' || obj == null) {
    return obj
  }
  let result
  if (obj instanceof Array) {
    result = []
  } else {
    result = {}
  }
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      result[key] = deepClone(obj[key])
    }
  }
  return result
}
